#include "parse.h"

QTextStream cout(stdout,QIODevice::ReadWrite);


int GetParseNum(const QString str)
{
    if(str.compare("get") == 0) return COMMAND_GET;
    if(str.compare("set") == 0) return COMMAND_SET;
    if(str.compare("up") == 0) return COMMAND_UPDATE;
    if(str.compare("rm") == 0) return COMMAND_REMOVE;
    if(str.compare("ls") == 0) return COMMAND_LIST;
    if(str.compare("use") == 0) return COMMAND_USE;
    if(str.compare("quit") == 0) return COMMAND_QUIT;
    return 0;
}

void Command_Error(int Error_Macro)
{
    if(Error_Macro == 0) return;
    switch(Error_Macro)
    {
        case INVALID_COMMAND:
            cout<<"Invalid Command"<<endl;
        break;
        case INVAILD_SIZE:
            cout<<"Invalid Size"<<endl;
        break;
        default:
            cout<<"Undefined Error"<<endl;
    }
    return ;
}

int Command_Parse(QHash<QString,QString> *Hash,QString * str)
{
    QStringList parse;
    Persistence persis;
    Persis conf;
    if(str->isEmpty() || str->isNull()) return INVALID_COMMAND;
    if((parse = Command_Lex(str)).isEmpty()) return INVALID_COMMAND;
    cout<<parse.at(0)<<endl;
    switch(GetParseNum(parse.at(0)))
    {
        case COMMAND_GET:
            cout<<"Result: "<<GetHashValueByKey(Hash,&parse.at(1))<<endl;
        break;
        case COMMAND_SET:
            if(SetHash(Hash,&parse.at(1),&parse.at(2)) == 0)cout<<"Result:Set Success ;)"<<endl;
        break;
        case COMMAND_UPDATE:
//            cout<<"up"<<endl;
            if(UpdateHashByKey(Hash,&parse.at(1),&parse.at(2)) == 0)cout<<"Result:Update Success ;)"<<endl;
        break;
        case COMMAND_REMOVE:
//            cout<<"rm"<<endl;
            if(DelHashByKey(Hash,&parse.at(1)) == 0)cout<<"Result:Delete Success ;)"<<endl;
        break;
        case COMMAND_LIST:
        {
//            cout<<"ls"<<endl;
            int show_size = 0;
            if((show_size = parse.at(1).toInt()) == false) {cout<<"Map total: "<<Hash->size()<<endl;return INVAILD_SIZE;}
            if(ShowHashList(Hash,show_size) != 0) return INVAILD_SIZE;

        }break;
        case COMMAND_USE:
        {
             persis.UsageTheDBFile(&conf.DBDir,&parse.at(1));Command
        }
        break;
        case COMMAND_QUIT:
        {
            return 0;
        }
        break;
        default:
            cout<<"Undefined Error"<<endl;
        break;
    }

    return 0;
}

QStringList Command_Lex(QString * str)
{
    QStringList strmap = str->split(' ');
    for(int i = 0;i < strmap.size();++i)
        if(strmap.at(i).compare(" ") == 0)strmap.removeAt(i);
//    cout<<"---------"<<strmap.at(0)<<"-----"<<endl;
    if(GetParseNum(strmap.at(0)) == 0 || strmap.size() <= 1) {return QStringList();}
//    cout<<"asdsafas"<<endl;
    return strmap;
}
